package com.lsh.oms.core.proxy.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lsh.oms.core.redis.RedisTemplate;
import com.lsh.oms.core.utils.http.HttpClientTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;

/**
 * Project Name: GPSUtil
 * 北京链商电子商务有限公司
 * @author : wangliutao
 * Date: 19/1/31
 * Package Name: com.lsh.oms.core.utils.gps
 * Description:
 */
@Slf4j
@Component
public class GaoDeProxy implements InitializingBean {
    private static final String BICYCLING_DISTANCE_URL = "https://restapi.amap.com/v4/direction/bicycling";
    private static final String GAO_DE_MAP_KEY = "GAO_DE_MAP_KEY";

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${gaode.key}")
    private String gaodeKey;

    /**
     * 请求高德地图，计算骑行路线
     *
     * @return
     */
    public BigDecimal obtainBicyclingDistance(String originLng, String originLat, String destinationLng, String destinationLat) {
        BigDecimal distance = null;
        String origin = originLng + "," + originLat;
        String destination = destinationLng + "," + destinationLat;
        JSONObject jsonObject = this.obtainBicyclingRoute(origin, destination);
        if (jsonObject == null || jsonObject.isEmpty()) {
            return null;
        }

        JSONObject data = jsonObject.getJSONObject("data");
        if (data != null && !data.isEmpty()) {
            JSONArray paths = data.getJSONArray("paths");
            if (paths != null && paths.size() > 0) {
                JSONObject path = paths.getJSONObject(0);
                if (path != null && !path.isEmpty()) {
                    distance = path.getBigDecimal("distance");
                }
            }
        }

        return distance;
    }

    /**
     * 请求高德地图，计算骑行路线
     *
     * @return
     */
    public JSONObject obtainBicyclingRoute(String origin, String destination) {
//        String gaoDeKey = this.getGaoDeKey();
        String url = BICYCLING_DISTANCE_URL;
        HashMap<String, Object> params = new HashMap<>();
        params.put("key", gaodeKey);
        params.put("origin", origin);
        params.put("destination", destination);

        try {
            log.info("[POST][amap][URI={}] content: {}", url, JSON.toJSONString(params));
            String response = HttpClientTemplate.doGet(BICYCLING_DISTANCE_URL, params);
            log.info("[POST][amap][URI={}] response: {}", url, response);
            System.out.println(response);

            if (StringUtils.isEmpty(response)) {
                return new JSONObject();
            }

            JSONObject json = JSON.parseObject(response);
            if (json == null || json.size() == 0) {
                return new JSONObject();
            }
            String code = json.getString("errcode");

            if (!"0".equals(code)) {
//                throw new BusinessException(ReturnCode.REQUEST_FAIL, "请求高德地图失败，失败原因：" + json.getString("errmsg"));
                return new JSONObject();
            }

            return json;
        } catch (Exception e) {
            log.error("请求高德地图失败", e);
            return new JSONObject();
        }
    }

    /**
     * 从Redis中获取，请求高德API使用的key
     *
     * @return
     */
    private String getGaoDeKey() {
        String key = null;
        try {
            key = redisTemplate.get(GAO_DE_MAP_KEY);
        } catch (Exception e) {
            log.error("请求redis异常");
        }

        return key;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        try {
//            String gaoDeKey = "5931755fd1c5f54b07f6854df66b22f8"; //个人
            String gaoDeKey = gaodeKey;
            String key = redisTemplate.get(GAO_DE_MAP_KEY);
            if (StringUtils.isEmpty(key)) {
                redisTemplate.set(GAO_DE_MAP_KEY, gaoDeKey);
            }
        } catch (Exception e) {
            log.error("初始化，高德key，请求redis异常");
        }
    }

    /*---------------------------------高德-------------------------------------*/

    private static double EARTH_RADIUS = 6378.137;

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     * 通过经纬度获取距离(单位：米)
     *
     * @param lat1
     * @param lng1
     * @param lat2
     * @param lng2
     * @return
     */
    public double getDistance(double lat1, double lng1, double lat2, double lng2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radLat1) * Math.cos(radLat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000d) / 10000d;
        s = s * 1000;
        return s;
    }

    public static void main(String[] args) {
        GaoDeProxy gaoDeProxy = new GaoDeProxy();
        BigDecimal bigDecimal = gaoDeProxy.obtainBicyclingDistance("116.45925", "39.910031", "116.587922", "40.081577");
        System.out.println(bigDecimal);
    }
}


